// pages/order/order_list.js
var api = require('../../utils/api');
var wxpay = require('../../utils/wxpay');
Array.prototype.removeByValue = function (val) {
  for (var i = 0; i < this.length; i++) {
    if (this[i].seatId == val) {
      this.splice(i, 1);
      break;
    }
  }
}
Array.prototype.removeById = function (val) {
  for (var i = 0; i < this.length; i++) {
    if (this[i].id == val) {
      this.splice(i, 1);
      break;
    }
  }
}
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    "orderNo":"",
    "passengers":0,
    "seatTypeName":'',
    seats: [],
    tmpSeats: [],
    "postParams": {
      "arrive": "",
      "arriveTime": "",
      "createId": "",
      "depTime": "",
      "departure": "",
      "isRandomSeat": "",
      "orderNo": "",
      "orderStatus": 0,
      "orderType": 0,
      "staId": "",
      "timeConsuming": "",
      "totalCount": 0,
      "totalPrice": 0,
      "trainNo": "",
      "userList": [
        {
          "cardNo": "",
          "cardType": "",
          "id": 0,
          "name": "",
          "price": "",
          "seatId": 0,
          "seatNo": "",
          "seatType": "",
          "ticketType": ""
        }
      ]
    },
    "cellId": "-1", 
    "price": "0",
    "totalPrice": "0",
    person_list:[],
    searchParams:{},
    ticket_detail:{},
    autoplay: false,
    hiddenmodalnotice:true,
    hiddenmodalinput:true,
    hardbgcolor:'',
    hardcolor:'',
    hardborder:'',
    softbgcolor:'',
    softcolor:'',
    softborder:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
    var id = options.id;
    var departureCode = options.departureCode;
    var arriveCode = options.arriveCode;
    this.setData({
      searchParams:{
        "staId": id,
        "departureCode": departureCode,
        "arriveCode": arriveCode
      }
    });
    this.getTicketDetail();
  },
  getTicketDetail:function(){
    var params = this.data.searchParams;
    var url = api.getTicketDetailUrl();
    var that = this;
    api.request(url, 'POST', params, function (res, err) {
      that.setData({ ticket_detail: res });
      that.setOrderData(res);
    });
  }, 
  setOrderData: function (options) {
    this.data.postParams.arrive = options.arriveName;
    this.data.postParams.arriveTime = options.arriveTime;
    this.data.postParams.depTime = options.departureTime;
    this.data.postParams.departure = options.departureName;
    this.data.postParams.isRandomSeat  = 0;
    this.data.postParams.staId = options.staId;
    this.data.postParams.timeConsuming = options.costTime;
    this.data.postParams.totalCount = this.data.person_list.length;
    this.data.postParams.totalPrice =100;
    //  this.data.totalPrice;
    this.data.postParams.trainNo = options.trainNo;
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.updateTotalPrice();
  },
  updateTotalPrice:function(){
    
    var price = this.data.price;
    var personSize = this.data.person_list.length;
    var totalPrice = price * personSize;
    this.setData({
      totalPrice: totalPrice
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
   
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }, tapName: function (e) {
    
    var formId=e.detail.formId;
    var userlist=[];
    var list = this.data.person_list;
    var seatList = this.data.seats;
    if (null == list || list.length==0){
      wx.showToast({
        title: '请先选择乘客',
        icon: 'succes',
        duration: 1000,
        mask: true
      });
      return;
    }
    
    var isRadom=false;
    for(var i=0;i<list.length;i++){
      
      var person = list[i];

      var cardNo = person.cardNo;
      var cardType = person.cardType;
      var id = person.id;
      var name = person.name;
      var price = this.data.price;
      var seatId = ''; 
      var seatNo = '';
      if (seatList.length>0){
        seatId = seatList[i].seatId;
        seatNo = seatList[i].seatNo;
        isRadom=true;
      }
      var seatType = this.data.cellId;
      var ticketType = person.cardType;
      
      var userObj = { 
      "cardNo": cardNo, 
      "cardType": cardType, 
      "id": id, 
      "name": name,
      "price": price,
      "seatId": seatId,
      "seatNo": seatNo,
      "seatType": seatType,
      "ticketType": seatType
      };
      userlist.push(userObj);
    }
    
    if(isRadom){
      this.data.postParams.isRandomSeat=1;
    }
    console.log(app.globalData);
    var createId = app.globalData.opendId;
    this.data.postParams.createId = createId;

    this.data.postParams.totalCount = userlist.length;
    var totalPrice = this.data.totalPrice;
    this.data.postParams.totalPrice = totalPrice;
    this.data.postParams.userList = userlist;
    this.data.postParams.formId = formId;
    var params= this.data.postParams;
    var url=api.createOrderUrl();
    var that = this;
    console.log(params);
    api.request(url, 'POST', params, function (res, err) {
       
      if (err){
        wx.showToast({
          title: err.msg,
          icon: 'succes',
          duration: 1000,
          mask: true
        });
        return;
       }
       var return_code = res.return_code;
       that.data.orderNo = res.orderNo
        //微信统一下单成功
       var result_code = res.result_code;
       if (return_code == 'SUCCESS' && result_code == 'SUCCESS') {
          var timeStamp = res.timeStamp;
          var nonceStr = res.nonce_str;
          var prepay_id = "prepay_id=" + res.prepay_id;
          var signType = "MD5";
          var paySign = res.paySign;
          var payParams = {
            timeStamp: timeStamp,
            nonceStr: nonceStr,
            "package": prepay_id,
            signType: signType,
            paySign: paySign
          };

          wxpay.requestPayment(payParams, that.paySuccess, that.payFail, that.payComplete);

        }else{
          that.payFail();
        }
  
    });
   
  },
  paySuccess: function () {
    var totalPrice = this.data.postParams.totalPrice;
    var orderNo = this.data.orderNo;
    wxpay.payCallback(orderNo);
    wx.navigateTo({
      url: '../paymentresult/payment_result?totalPrice=' + totalPrice + "&orderNo=" + orderNo
    })
  }, payFail: function () {
    
    var orderNo = this.data.orderNo;
    wx.navigateTo({
      url: '../payment/payment?orderNo=' + orderNo
    })
  }, payComplete: function () {

  },addName: function () {
    wx.navigateTo({
      url: '../personlist/person_list'
    })
  },
  bindPick:function(e){
    var count = this.data.person_list.length;
    var seatList=this.data.tmpSeats;
    var seatid = e.currentTarget.dataset.seatid;

    if (count==0){
      wx.showToast({
        title: '请先选择乘客',
        icon: 'succes',
        duration: 1000,
        mask: true
      });
      return;
    }
    var isCheck=false;
    for (var i = 0; i < seatList.length;i++){
      if (seatid == seatList[i].seatId){
        isCheck=true;
      }
    }
    if (count == seatList.length) {
      if (!isCheck){
        wx.showToast({
          title: '已超出旅客人数',
          icon: 'succes',
          duration: 1000,
          mask: true
        });
        return;
        }
    }

    var rowNum = e.currentTarget.dataset.rownum;
    var seatNo = e.currentTarget.dataset.seatno;
    var coachno = e.currentTarget.dataset.coachno;
    var coachType = e.currentTarget.dataset.coachtype;
    var id = rowNum + seatNo + coachno + coachType;

    var persons = this.data.person_list;

    var list = this.data.ticket_detail.optionalSeats;
    // var per
    for(var i=0;i<list.length;i++){
      var rows = list[i].rows;
      for (var row= 0;row<rows.length;row++){
        var rowLists = rows[row].rowList;
        for (var seat=0; seat < rowLists.length; seat++) {
          var rowSeatId = rowLists[seat].seatId;
          if (rowSeatId == seatid){
            var isCheck = rowLists[seat].isCheck;
            if (isCheck){
              rowLists[seat].isCheck=false;
              seatList.removeByValue(seatid);
            }else{
              rowLists[seat].isCheck = true;
              seatList.push(rowLists[seat]);
            }
            this.updateData(list);
            return false;
          }
        }
      }
    }
  },
  //取消全选
  clearSeat:function(){
    
    var list = this.data.ticket_detail.optionalSeats;
    for (var i = 0; i < list.length; i++) {
      var rows = list[i].rows;
      for (var row = 0; row < rows.length; row++) {
        var rowLists = rows[row].rowList;
        for (var seat = 0; seat < rowLists.length; seat++)          {
            var rowSeatId = rowLists[seat].seatId;
            rowLists[seat].isCheck = false;
         }
        }
      }
    var ticketDetail = this.data.ticket_detail;
    ticketDetail.optionalSeats = list;
    this.setData({
      ticket_detail: ticketDetail,
      tmpSeats:[]
    });
    },
    //确认选座
  confirmBtn:function(){
    var persons = this.data.person_list;
    var seats = this.data.tmpSeats
      
    if (seats.length!=0 && seats.length != persons.length) {
      wx.showToast({
        title: '请先选择座位',
        icon: 'succes',
        duration: 1000,
        mask: true
      });
      return;
    }

    this.confirmSeat();
    this.hideModal();
   
  },
  confirmSeat: function () {
    this.data.seats = [];
    var list = this.data.ticket_detail.optionalSeats;
    
    var persons = this.data.person_list;
    var totalPrice=0;
    for (var i = 0; i < list.length; i++) {
      var objList = list[i];
      var rows = objList.rows;
      for (var row = 0; row < rows.length; row++) {
        var rowLists = rows[row].rowList;
        for (var seat = 0; seat < rowLists.length; seat++)          {
          if (rowLists[seat].isCheck){
            var seatId = rowLists[seat].seatId;
            var seatNo = rowLists[seat].seatNo; 
            var seatType = rowLists[seat].seatType;
            var seatName='';
            if (seatNo=='atop'){
              seatName='上';
            }else if (seatNo == 'bmiddle') {
              seatName = '中';
            }else{
              seatName = '下';
            }
            
            var seatPrice = this.getSeatPrice(seatType);
            totalPrice += parseFloat(seatPrice);;
            var rowNum = rows[row].rowNum;
            var coachno = objList.coachNo;
            var coachType = objList.coachType;
            var seatTypeName = coachno+ rowNum +'号'+ seatName  + ' '+coachType;
            var obj = new Object();
            obj.seatType = seatType;
            obj.seatId = seatId;
            obj.seatNo = rows[row].rowNum;
            obj.seatTypeName = seatTypeName; 
            this.data.seats.push(obj);
          }
        }
      }
    }

var seats = this.data.seats;
    for (var i = 0; i < persons.length; i++) {
      var seatTypeName='';
      if (seats[i]){
        seatTypeName = seats[i].seatTypeName;
      }
      persons[i].seatTypeName = seatTypeName;
    }
    this.setData({
      person_list: persons,
      totalPrice: totalPrice
    });
  },
  getSeatPrice:function(seatType){
    var list = this.data.ticket_detail.seats;
    for (var i=0; i < list.length;i++){
      if (seatType == list[i].seatTypeId){
        return list[i].price;
      }
    }
  },
  updateData: function (list){

    var ticketDetail = this.data.ticket_detail;       
    ticketDetail.optionalSeats = list;
   
    this.setData({
      ticket_detail: ticketDetail
    });
  },
  gpshowModal: function () {
    this.setData({
      hiddenmodalnotice: !this.data.hiddenmodalnotice
    })
  },
  gpcancel: function(){
    this.setData({
      hiddenmodalnotice: true
    })
  },
  gpconfirm: function () {
    this.setData({
      hiddenmodalnotice: !this.data.hiddenmodalnotice
    })
  },
  modalinput: function (e){
    var url = api.getTimeTable();
    var that = this;
    api.request(url, 'GET', { 'staId': e.currentTarget.dataset.statid }, function (res, err) {
      that.setData({
        hiddenmodalinput: !that.data.hiddenmodalinput,
        timeTableList: res
      })
    });

    /*
    this.setData({
      hiddenmodalinput: !this.data.hiddenmodalinput
    })*/
  },
  skcancel: function () {
    this.setData({
      hiddenmodalinput: true
    })
  },
  skconfirm: function () {
    this.setData({
      hiddenmodalinput: !this.data.hiddenmodalinput
    })
  },
  hardSeat: function(e){
    
    var id = e.target.dataset.id;
    var price = e.target.dataset.price;
    var seatTypeName = e.target.dataset.seatname;
    
    this.setData({
      cellId: id,
      price: price,
      seatTypeName: seatTypeName
    });
    this.updateTotalPrice();
  },
  /**在线选座弹框
   * 
   */
  showModal: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  hideModal: function () {
    
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },delPer:function(e){
	  var id = e.currentTarget.dataset.id;
	  var person_list = this.data.person_list;

    var seats = this.data.seats;
	  for(var i=0; i<person_list.length; i++){
		  if(person_list[i].id==id) {
        person_list.removeById(id);
        if (seats[i]){
          seats.removeByValue(seats[i].seatId);
        }
		  }
		  
	  }
	  this.setData({
		  person_list: person_list
	  });
	  
  }
})
